package cn.vihub.controller;

import cn.hutool.crypto.SecureUtil;
import cn.vihub.client.user.UserFeignClient;
import cn.vihub.handler.MyRuntimeException;
import cn.vihub.param.ShopUserParam;
import cn.vihub.param.TokenParam;
import cn.vihub.pojo.ShopUser;
import cn.vihub.service.TokenService;
import cn.vihub.utils.Result;
import cn.vihub.vo.TokenVo;
import lombok.RequiredArgsConstructor;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PostMapping;
import org.springframework.web.bind.annotation.RequestBody;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;

@RestController
@RequiredArgsConstructor
@RequestMapping("shop-auth/login")
public class LoginController {

    @Autowired
    private TokenService tokenService;

    private final UserFeignClient userFeignClient;

    /**
     * 登录获取token接口
     * @return
     */
    @PostMapping("getAccessToken")
    public Result<TokenVo> getAccessToken(@RequestBody ShopUserParam shopUserParam){

        // 获取用户信息
        ShopUser shopUser = userFeignClient.getUserByUsername(shopUserParam.getUsername());
        if (shopUser == null){
            throw new MyRuntimeException("用户不存在");
        }

        if (!shopUser.getPassword().equals(SecureUtil.md5(shopUserParam.getPassword()))){
            throw new MyRuntimeException("密码错误");
        }


        return Result.success(tokenService.createAccessToken(1, "user1"));
    }

    @PostMapping("getRefreshToken")
    public Result<TokenVo> getRefreshToken(@RequestBody TokenParam tokenParam){
        return Result.success(tokenService.createRefreshToken(tokenParam.getRefreshToken()));
    }

}
